'use strict';
angular.module('hanxinBroker').directive('checkIsSame', function checkIsSame() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function (scope, element, attrs, ngModel) {
      ngModel.$parsers.push(function (value) {
        if (_.isUndefined(value)) {
          return undefined;
        }

        var anotherValue = scope.$eval(attrs.checkIsSame);
        var isSame = value === anotherValue;
        ngModel.$setValidity('same', isSame);

        return isSame ? value : undefined;
      });
      scope.$watch(
        function () {
          return scope.$eval(attrs.checkIsSame);
        },
        function (anotherValue) {
          var isSame = ngModel.$modelValue === anotherValue;
          ngModel.$setValidity('same', isSame);
        }
      );
    }
  };
});
